package thread.synchronize;

/**
 * @author liweimin
 * @date 2021/4/29 14:48
 * @since
 */
public class DeadLockTest {

    public static void main(String[] args) {
        SubThread subThread1 = new SubThread();
        subThread1.setName("A");
        subThread1.start();


        SubThread subThread2 = new SubThread();
        subThread2.setName("B");
        subThread2.start();
    }

    static class SubThread extends Thread {
        private static final Object lock1 = new Object();
        private static final Object lock2 = new Object();


        @Override
        public void run() {
            if ("A".equals(Thread.currentThread().getName())) {

                synchronized (lock1) {
                    System.out.println("线程A获得了lock1，还需要获得lock2");
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    synchronized (lock2) {
                        System.out.println("线程A获得了lock1，又获得了lock2");
                    }
                }

            }
            if ("B".equals(Thread.currentThread().getName())) {
                synchronized (lock2) {
                    System.out.println("线程B获得了lock2，还需要获得lock1");
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    synchronized (lock1) {
                        System.out.println("线程B获得了lock2，又获得了lock1");
                    }
                }

            }
        }
    }
}
